package com.kcht.rd30;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Set;

@Component
@Slf4j
public class CalibrationTime {
    private Set<String> ips;
    private int port=10006;
    @Autowired
    private CommonMapper mapper;
    @Value("${cali.scheduled-cron}")
    private String cron;
    @Value("${cali.recv-timeout}")
    private Integer recvTimeout;

    @PostConstruct
    public void init(){
        ips = mapper.getAllDeviceIp();
        /*删除这几个不稳定的，每个使用情况都不同*/
//        ips.remove("192.168.11.158");
//        ips.remove("192.168.11.160");
//        ips.remove("192.168.11.161");
        log.info("定时表达式 ---> "+cron);
    }

    @Scheduled(cron = "${cali.scheduled-cron}")
    public void calibrator(){
        ips.forEach((ip)->{
            try(ZContext context = new ZContext()){
                try(ZMQ.Socket req = context.createSocket(SocketType.REQ)){
                    req.setHeartbeatTimeout(recvTimeout);
                    req.setReceiveTimeOut(recvTimeout);
                    req.setSendTimeOut(recvTimeout);
                    req.connect("tcp://"+ip+":"+port);
                    pub_msg.Pub.pub_request request = pub_msg.Pub.pub_request.getDefaultInstance();
                    LocalDateTime now = LocalDateTime.now();
                    int hour=now.getHour();
                    if(hour>=8){
                        hour=hour-8;
                    }
                    request=request.toBuilder()
                            .setType(pub_msg.Pub.pub_request.HeadType.setSystemTime)
                            .setSysTime(pub_msg.Pub.SysTimePara.getDefaultInstance().toBuilder()
                                    .setSecond(now.getSecond())
                                    .setMinute(now.getMinute())
                                    .setHour(hour)
                                    .setMday(now.getDayOfMonth())
                                    .setMonth(now.getMonthValue())
                                    .setYear(now.getYear())).build();
                    req.send(request.toByteArray());
                    final byte[] recv = req.recv();
                    if(recv!=null&&pub_msg.Pub.pub_response.parseFrom(recv).getStatus()==0){
                        log.info(ip+"已校对时间 ---> "+now);
                    }else{
                        log.info(ip+"未能正确校对时间 ---> "+now);
                    }
                }
            }catch (Throwable e){
                e.printStackTrace();
            }
        });
    }
}
